package cn.com.hbhgkj.webapp.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;

import cn.com.hbhgkj.Constants;
import cn.com.hbhgkj.ReviewCode;
import cn.com.hbhgkj.dao.SearchException;
import cn.com.hbhgkj.model.CopyrightAlteration;
import cn.com.hbhgkj.model.LabelValue;
import cn.com.hbhgkj.service.CopyrightAlterationManager;

import com.opensymphony.xwork2.Preparable;

public class CopyrightAlterationAction extends BaseAction implements Preparable {
	private CopyrightAlterationManager copyrightAlterationManager;
	private List copyrightAlterations;
	private CopyrightAlteration copyrightAlteration;
	private Long id;
	private String query;

	public void setCopyrightAlterationManager(
			CopyrightAlterationManager copyrightAlterationManager) {
		this.copyrightAlterationManager = copyrightAlterationManager;
	}

	public List getCopyrightAlterations() {
		return copyrightAlterations;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {
		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String copyrightAlterationId = getRequest().getParameter(
					"copyrightAlteration.id");
			if (copyrightAlterationId != null
					&& !copyrightAlterationId.equals("")) {
				copyrightAlteration = copyrightAlterationManager.get(new Long(
						copyrightAlterationId));
			}
		}
	}

	public void setQ(String q) {
		this.query = q;
	}
	

	public String getQuery() {
		return query;
	}

	public String list() {
		try {
			if (administrator()) {
				copyrightAlterations = copyrightAlterationManager.search(query,
						CopyrightAlteration.class);
			} else {
				copyrightAlterations = copyrightAlterationManager
						.findByApplicant(getCurrentUser());
			}
		} catch (SearchException se) {
			addActionError(se.getMessage());
			copyrightAlterations = copyrightAlterationManager.getAll();
		}
		return SUCCESS;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public CopyrightAlteration getCopyrightAlteration() {
		return copyrightAlteration;
	}

	public void setCopyrightAlteration(CopyrightAlteration copyrightAlteration) {
		this.copyrightAlteration = copyrightAlteration;
	}

	public String delete() {
		copyrightAlterationManager.remove(copyrightAlteration.getId());
		saveMessage(getText("copyrightAlteration.deleted"));

		return SUCCESS;
	}

	public String edit() {
		if (id != null) {
			copyrightAlteration = copyrightAlterationManager.get(id);
		} else {
			copyrightAlteration = new CopyrightAlteration();
			copyrightAlteration.setSqrname(getCurrentUser().getCompanyName());
			copyrightAlteration.setSqraddress(getCurrentUser().getAddress().getAddress());
			copyrightAlteration.setSqrpostCode(getCurrentUser().getAddress().getPostalCode());
			copyrightAlteration.setSqrcontactPerson(getCurrentUser().getContact());
			copyrightAlteration.setSqrphone(getCurrentUser().getContactNumber());
			copyrightAlteration.setSqremail(getCurrentUser().getEmail());
			copyrightAlteration.setSqrmobile(getCurrentUser().getPhoneNumber());
			copyrightAlteration.setSqrfax(getCurrentUser().getFax());
		}

		return SUCCESS;
	}

	public String save() throws Exception {
		if (cancel != null) {
			return "cancel";
		}

		if (delete != null) {
			return delete();
		}

		boolean isNew = (copyrightAlteration.getId() == null);

		Date curDate = new Date();
		if (isNew) {
			copyrightAlteration.setApplicant(this.getCurrentUser());
			copyrightAlteration.setApplyTime(curDate);
			copyrightAlteration.setLoginId(Constants.AGENT_USERNAME);

		}

		copyrightAlteration.setState(ReviewCode.PENDING_REVIEW.getValue());
		copyrightAlteration.setUpdateTime(curDate);

		copyrightAlterationManager.save(copyrightAlteration);

		String key = (isNew) ? "copyrightAlteration.added"
				: "copyrightAlteration.updated";
		saveMessage(getText(key));

		if (!isNew) {
			return INPUT;
		} else {
			return SUCCESS;
		}
	}

	// method of ADMIN role
	public String approve() {
		// validate current user
		if (!administrator()) {
			throw new AccessDeniedException(
					"Access Denied: Only administrators are allowed to review.");
		}
		try {

			copyrightAlterationManager.review(this.getCurrentUser(),
					copyrightAlteration, ReviewCode.PASS);
		} catch (Exception e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	public String refuse() {
		// validate current user
		if (!administrator()) {
			throw new AccessDeniedException(
					"Access Denied: Only administrators are allowed to review.");
		}
		try {
			copyrightAlterationManager.review(this.getCurrentUser(),
					copyrightAlteration, ReviewCode.FAIL);
		} catch (Exception e) {
			addActionError(e.getMessage());
		}
		return SUCCESS;
	}

	private List<LabelValue> alterationTypeList = new ArrayList<LabelValue>();
	private List<LabelValue> supplyTypeList = new ArrayList<LabelValue>();

	private Map<String, String> constantValues = new HashMap<String, String>();

	public synchronized Map<String, String> getConstantValues() {
		if (constantValues.isEmpty()) {
			constantValues.put("copyrightAlteration.applyingType.alteration",
					"变更登记");
			constantValues.put("copyrightAlteration.applyingType.supply",
					"补充登记");

			constantValues.put("copyrightAlteration.originalRegType.reg",
					"软件著作权登记");
			constantValues.put(
					"copyrightAlteration.originalRegType.transferReg",
					"软件著作权转让合同登记");
			constantValues.put(
					"copyrightAlteration.originalRegType.proprietaryReg",
					"软件著作权专有许可合同登记");
		}
		return constantValues;
	}

	public synchronized List<LabelValue> getAlterationTypeList() {
		if (alterationTypeList.size() == 0) {
			alterationTypeList = new ArrayList<LabelValue>();
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.default"), ""));
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.softwareName"),
					"软件名称"));
			alterationTypeList
					.add(new LabelValue(
							getText("copyrightAlteration.alterationType.copyrighterName"),
							"著作权人姓名或名称"));
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.transferor"),
					"转让方"));
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.transferee"),
					"受让方"));
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.licensor"),
					"许可方"));
			alterationTypeList.add(new LabelValue(
					getText("copyrightAlteration.alterationType.licensee"),
					"被许可方"));

		}
		return alterationTypeList;
	}

	public synchronized List<LabelValue> getSupplyTypeList() {
		if (supplyTypeList.size() == 0) {
			supplyTypeList = new ArrayList<LabelValue>();
			supplyTypeList.add(new LabelValue(
					getText("copyrightAlteration.supplyType.default"), ""));
			supplyTypeList.add(new LabelValue(
					getText("copyrightAlteration.supplyType.firstPublishDate"),
					"首次发表日期"));

		}
		return supplyTypeList;
	}

	@Override
	public void validate() {
		super.validate();

		String beforeContent = "";
		String afterContent = "";
		String alerationType = "";

		if (this.copyrightAlteration.getApplyingType().equals("变更登记")) {
			alerationType = "copyrightAlteration.alterationType";
			beforeContent = "copyrightAlteration.originalContent";
			afterContent = "copyrightAlteration.alteredContent";
		} else {
			alerationType = "copyrightAlteration.supplyType";
			beforeContent = "copyrightAlteration.supplyOrigContent";
			afterContent = "copyrightAlteration.supplyNewlyContent";
		}

		for (String each : alterationTypes) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText("errors.requiredField",new String[]{getText(alerationType)}));
				return;
			}
		}

		for (String each : originalContents) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText("errors.requiredField",new String[]{getText(beforeContent)}));
				return;
			}

			if (each.length() > 400) {
				this.addFieldError(
						beforeContent,
						getText("errors.maxlength",
								new String[] { "400" }));
				return;
			}
		}

		for (String each : alteredContents) {
			if (StringUtils.isEmpty(each)) {
				this.addActionError(getText("errors.requiredField",new String[]{getText(afterContent)}));
				return;
			}

			if (each.length() > 400) {
				this.addFieldError(
						afterContent,
						getText("errors.maxlength",
								new String[] { "400" }));
				return;
			}
		}
	}

	private String[] alterationTypes;
	private String[] originalContents;
	private String[] alteredContents;

	public String[] getAlterationTypes() {
		return alterationTypes;
	}

	public void setAlterationTypes(String[] alterationTypes) {
		this.alterationTypes = alterationTypes;
	}

	public String[] getAlteredContents() {
		return alteredContents;
	}

	public void setAlteredContents(String[] alteredContents) {
		this.alteredContents = alteredContents;
	}

	public void setAlterationTypeList(List<LabelValue> alterationTypeList) {
		this.alterationTypeList = alterationTypeList;
	}

	public String[] getOriginalContents() {
		return originalContents;
	}

	public void setOriginalContents(String[] originalContents) {
		this.originalContents = originalContents;
	}

}